package com.zhkj.txg.module.find.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.find.adapter.FindPictureAdapter
import com.zhkj.txg.module.find.entity.AssociateProductEntity
import com.zhkj.txg.module.find.entity.FindPictureEntity
import com.zhkj.txg.module.find.vm.FindViewModel
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.MatisseUtils
import com.zhkj.txg.utils.TextWatcherWrapper
import com.zhihu.matisse.Matisse
import kotlinx.android.synthetic.main.activity_find_article_publish.*

class FindArticlePublishActivity : ViewModelActivity<FindViewModel>() {

    companion object {
        fun publishArticle(fragment: Fragment, requestCode: Int) {
            val intent = Intent(fragment.context, FindArticlePublishActivity::class.java)
            fragment.startActivityForResult(intent, requestCode)
        }
    }

    override fun setViewModel(): FindViewModel = createViewModel()
    override fun statusTitleBar(): View? = titlePublish
    override val layoutResId: Int = R.layout.activity_find_article_publish

    private val requestCodePicture = 10000
    private val requestCodeProduct = 10001
    private val MAX_COUNT = 9
    private val pictureAdapter = FindPictureAdapter(
        MAX_COUNT
    ).apply {
        setOnItemClickListener { _, _, position ->
            // 添加按钮监听
            if (data[position].itemType == FindPictureEntity.TYPE_ADD) {
                requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, {
                    selectPicture(MAX_COUNT - getRealPictureCount())
                }, { toast(getString(R.string.read_permission_deny)) })
            }
        }
        // 删除按钮监听
        setOnItemChildClickListener { _, _, position ->
            run {
                deletePicture(position)
                // 判断发布按钮是否可点击
                titlePublish.setRightButtonEnable(
                    etArticlePublish.text?.length ?: 0 > 0 && data.size >= 2
                )
            }
        }
    }

    override fun initViewModel() {
        viewModel.publishArticleLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip, true)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                toast(it.response?.msg ?: getString(R.string.publish_success))
//                setResult(RESULT_OK, intent)
                finish()
            }
        })
    }

    override fun initUI() {
        rvArticlePublish.layoutManager = GridLayoutManager(this, 3)
        rvArticlePublish.adapter = pictureAdapter
        // 心得字数监听
        etArticlePublish.addTextChangedListener(TextWatcherWrapper {
            val length = it?.length ?: 0
            tvArticleCount.text = "${length}/300"
            // 判断发布按钮是否可点击
            titlePublish.setRightButtonEnable(length > 0 && pictureAdapter.data.size >= 2)
        })
        // 关联商品监听
        viewPublishProduct.setOnClickListener {
            FindArticleProductActivity.selectProduct(
                this@FindArticlePublishActivity,
                requestCodeProduct
            )
        }
        titlePublish.setRightClickListener(View.OnClickListener {
            viewModel.publishArticle(
                AccountManager.getToken(),
                etArticlePublish.text?.toString() ?: "",
                pictureAdapter.data
            )
        })

        titlePublish.setRightButtonEnable(false)
        showProduct(viewModel.selectProduct)
    }

    override fun initData() {
        pictureAdapter.addData(
            FindPictureEntity().apply {
                itemType = FindPictureEntity.TYPE_ADD
            })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == requestCodePicture) {
            // 构造已选照片参数，填充Adapter
            val selectPicList = Matisse.obtainPathResult(data)
            if (selectPicList.isNotEmpty()) {
                val list = mutableListOf<FindPictureEntity>()
                for (filePath in selectPicList) {
                    list.add(
                        FindPictureEntity(
                            filePath
                        ).apply {
                            itemType = FindPictureEntity.TYPE_PIC
                        })
                }
                pictureAdapter.addPicture(list)
                // 判断发布按钮是否可点击
                titlePublish.setRightButtonEnable(etArticlePublish.text?.length ?: 0 > 0)
            }
        } else if (resultCode == Activity.RESULT_OK && requestCode == requestCodeProduct) {
            // 判断是否关联商品
            val product = data?.getSerializableExtra("data") as? AssociateProductEntity
            viewModel.selectProduct = product
            showProduct(product)
        }
    }

    /**
     * 打开图片选择器
     */
    private fun selectPicture(selectNum: Int) {
        MatisseUtils.selectPicture(this, requestCodePicture, selectNum)
    }

    /**
     * 设置关联商品UI
     */
    private fun showProduct(product: AssociateProductEntity?) {
        if (product != null) {
            tvFindPublishAddProduct.visibility = View.GONE
            viewFindPublishProduct.visibility = View.VISIBLE
            ImageUtils.loadRoundCornerImage(this, ivFindPublishProduct, product.image)
            tvFindPublishProductTitle.text = product.goodsName
            tvFindPublishProductPrice.text = SpanUtil.setMoneySymbol(product.goodsPrice)
            tvProductMarketPrice.visibility = View.INVISIBLE
        } else {
            tvFindPublishAddProduct.visibility = View.VISIBLE
            viewFindPublishProduct.visibility = View.GONE
        }
    }
}